<template>
  <div>
    <app-head></app-head>
    <app-body>
      <div class="message-container">
        <!-- 顶部标题和切换标签 -->
        <div class="message-header">
          <div class="title">我的消息</div>
          <el-tabs v-model="activeTab" @tab-click="loadConversations">
            <el-tab-pane label="私聊消息" name="private"></el-tab-pane>
            <el-tab-pane label="商品咨询" name="item"></el-tab-pane>
          </el-tabs>
        </div>

        <!-- 消息列表 -->
        <div v-if="displayConversations.length > 0" class="conversation-list">
          <div 
            v-for="conv in displayConversations" 
            :key="conv.id"
            class="conversation-item"
            :class="{ 'unread': conv.unreadCount > 0 }"
            @click="openChat(conv)"
          >
            <el-avatar :src="conv.avatar" size="medium"></el-avatar>
            <div class="conversation-info">
              <div class="info-header">
                <span class="username">{{ conv.name }}</span>
                <span class="time">{{ formatTime(conv.lastMessageTime) }}</span>
              </div>
              <div class="preview">
                {{ conv.lastMessage }}
                <el-badge 
                  v-if="conv.unreadCount > 0" 
                  :value="conv.unreadCount" 
                  class="unread-badge"
                />
              </div>
            </div>
            <div v-if="conv.itemId" class="item-preview">
              <el-image
                style="width: 60px; height: 60px;"
                :src="conv.itemImage || conv.avatar"
                fit="cover"
              ></el-image>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-message">
          <img src="../../assets/NoMessage.png" alt="暂无消息">
          <p>还没有收到消息哦~</p>
        </div>

        <!-- 聊天对话框 -->
        <el-dialog
          :visible.sync="showChatDialog"
          width="60%"
          class="chat-dialog"
          :show-close="true"
          custom-class="custom-chat-dialog"
          @opened="focusInput"
          @closed="closeChat"
        >
          <template slot="title">
            <div class="chat-dialog-header">
              <el-avatar :size="40" :src="currentChat.avatar"></el-avatar>
              <div class="chat-dialog-title">
                <div class="chat-user-name">{{ currentChat.name }}</div>
                <div v-if="currentChat.userId" class="chat-user-id">ID: {{ currentChat.userId }}</div>
              </div>
              <el-button type="danger" size="small" @click="deleteChat" icon="el-icon-delete">删除聊天</el-button>
            </div>
          </template>

          <div class="chat-messages" ref="messageContainer">
            <div 
              v-for="(msg, index) in messages" 
              :key="index" 
              class="message-item"
              :class="{ 'self': msg.sender === currentUser }"
            >
              <div class="message-user">
                <el-avatar 
                  v-if="msg.sender !== currentUser"
                  :size="32" 
                  :src="currentChat.avatar" 
                />
                <span class="sender-name" v-if="msg.sender !== currentUser">
                  {{ currentChat.name }}
                </span>
                <span class="sender-name self-name" v-else>
                  {{ $globalData.userInfo.username || '我' }}
                </span>
                <el-avatar 
                  v-if="msg.sender === currentUser"
                  :size="32" 
                  :src="$globalData.userInfo.avatar" 
                />
              </div>
              <div class="message-content">{{ msg.content }}</div>
              <div class="message-time">{{ formatTime(msg.createTime) }}</div>
            </div>
          </div>

          <div class="chat-input-container">
            <el-input
              ref="messageInput"
              v-model="newMessage"
              type="textarea"
              :rows="3"
              placeholder="请输入消息..."
              @keyup.enter.native="sendMessage"
              class="chat-input"
            ></el-input>
            <el-button 
              type="primary" 
              @click="sendMessage"
              class="send-button"
            >
              发送
            </el-button>
          </div>
        </el-dialog>
      </div>
    </app-body>
  </div>
</template>

<script>
import AppHead from '../common/AppHeader.vue'
import AppBody from '../common/AppPageBody.vue'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import dayjs from 'dayjs'
import service, { forceLogout } from '../../utils/request'

// 获取token的辅助函数
const getToken = () => {
  const token = localStorage.getItem('token');
  return (token && token.trim()) || null;
};

export default {
  name: 'MessagePage',
  components: { AppHead, AppBody },
  data() {
    return {
      // WebSocket相关
      reconnectAttempts: 0,
      maxReconnectAttempts: 5,
      heartbeatInterval: null,
      privateSubscription: null,
      sentSubscription: null,
      stompClient: null,
      
      // 聊天相关
      currentUser: null,
      showChatDialog: false,
      messages: [],
      newMessage: '',
      
      // 会话相关
      activeTab: 'private',
      privateConversations: [],
      messageConversations: [],
      currentChat: {},
      
      // 其他
      defaultAvatars: []
    }
  },
  computed: {
    displayConversations() {
      return this.activeTab === 'private' ? this.privateConversations : this.messageConversations
    }
  },
  created() {
    this.checkAuth();
    this.loadConversations();
    this.initWebSocket();
    
    // 获取当前用户ID
    this.$api.getUserInfo().then(res => {
      if (res.status_code === 1 && res.data) {
        this.currentUser = res.data.id;
      }
    });
  },
  beforeDestroy() {
    this.disconnectWebSocket();
  },
  methods: {
    // 检查认证状态
    checkAuth() {
      if (!localStorage.getItem('token')) {
        this.$router.push('/login');
        return false;
      }
      return true;
    },
    
    // 加载会话列表
   // 加载会话列表
loadConversations() {
  // 加载私聊会话
  this.$api.service.get('/chat/private-conversations').then(res => {
    if (res.status_code === 1 && Array.isArray(res.data)) {
      const conversationMap = new Map();
      
      res.data.forEach(conv => {
        // 生成唯一会话key（排序后的用户ID组合）
        const participants = [conv.sender, conv.receiver].sort();
        const sessionKey = `private_${participants.join('_')}`;
        
        // 如果已存在会话，则更新最后消息
        if (conversationMap.has(sessionKey)) {
          const existing = conversationMap.get(sessionKey);
          if (new Date(conv.createTime) > new Date(existing.lastMessageTime)) {
            existing.lastMessage = conv.content;
            existing.lastMessageTime = conv.createTime;
            existing.unreadCount += conv.isRead ? 0 : 1;
          }
        } else {
          // 创建新会话 - 根据实际API响应结构调整
          const isReceiver = conv.receiver === this.currentUser;
          console.log("私聊isReceiver为",isReceiver);
          console.log("私聊信息为",conv);
          conversationMap.set(sessionKey, {
            id: sessionKey, 
            sessionKey,
            userId: isReceiver ? conv.sender : conv.receiver,
            name: isReceiver ? 
              (conv.senderName || `用户${conv.senderName}`) : 
              (conv.receiverName || `用户${conv.receiverName}`),
            avatar: isReceiver ? 
              (conv.senderAvatar || this.getDefaultAvatar(conv.sender)) : 
              (conv.receiverAvatar || this.getDefaultAvatar(conv.receiver)),
            lastMessage: conv.content,
            lastMessageTime: conv.createTime,
            unreadCount: conv.unreadCount || 0,
            // 保留原始数据用于调试
            rawData: conv
          });
        }
      });
      
      this.privateConversations = Array.from(conversationMap.values());
    }
  }).catch(error => {
    console.error('加载私聊会话失败:', error);
    this.$message.error('加载私聊会话失败');
  });

  // 加载商品咨询消息
  this.$api.service.get('/message/my').then(res => {
    if (res.status_code === 1) {
      this.messageConversations = res.data.map(msg => {
        // 解析图片列表字符串为数组
        let pictureList = [];
        try {
          pictureList = JSON.parse(msg.idle.pictureList);
        } catch (e) {
          console.error('解析图片列表失败:', e);
          pictureList = [];
        }
        
        // 获取第一张图片作为缩略图
        const itemImage = pictureList.length > 0 ? pictureList[0] : '';
        
        return {
          id: msg.id,
          itemId: msg.idleId,
          name: msg.idle.idleName || '商品咨询',
          avatar: msg.fromU.avatar || this.getDefaultAvatar(msg.userId),
          lastMessage: msg.content,
          lastMessageTime: msg.createTime,
          unreadCount: msg.isRead ? 0 : 1,
          itemImage: itemImage,
          fromUser: msg.fromU,
          idleInfo: msg.idle
        };
      });
    }
  }).catch(error => {
    console.error('获取商品咨询消息失败:', error);
    this.$message.error('获取商品咨询消息失败');
  });
},

// 获取默认头像
getDefaultAvatar(userId) {
  const defaultAvatars = [
    'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
  ];
  const index = userId ? userId % defaultAvatars.length : 0;
  return defaultAvatars[index];
},
    
    // 初始化WebSocket连接
    initWebSocket() {
      return new Promise((resolve, reject) => {
        // 断开旧连接
        if (this.stompClient && this.stompClient.connected) {
          this.stompClient.disconnect();
        }

        const socket = new SockJS('http://localhost:8081/ws');
        this.stompClient = Stomp.over(socket);
        this.stompClient.debug = () => {};

        // 定义 safeSend 方法
        this.stompClient.safeSend = (destination, body, headers = {}) => {
          return new Promise((resolveSend, rejectSend) => {
            if (!this.stompClient.connected) {
              rejectSend(new Error('STOMP 连接未就绪'));
              return;
            }
            try {
              this.stompClient.send(
                destination,
                { ...headers, 'content-type': 'application/json' },
                JSON.stringify(body)
              );
              resolveSend();
            } catch (e) {
              rejectSend(e);
            }
          });
        };

        const connectHeaders = {
          Authorization: `Bearer ${localStorage.getItem('token')}`,
          'X-User-ID': this.currentUser
        };

        this.stompClient.connect(connectHeaders, () => {
          console.log('✅ WebSocket连接成功');
          
          // 自动订阅关键通道
          this.subscribeToPrivateQueue();
          this.subscribeToSentQueue();
          
          // 启动心跳检测
          this.startHeartbeat();
          
          resolve(true);
        }, (error) => {
          console.error('连接失败:', error);
          this.handleConnectionError(error);
          reject(error);
        });
      });
    },
    
    // 断开WebSocket连接
    disconnectWebSocket() {
      if (this.stompClient) {
        clearInterval(this.heartbeatInterval);
        if (this.privateSubscription) this.privateSubscription.unsubscribe();
        if (this.sentSubscription) this.sentSubscription.unsubscribe();
        if (this.stompClient.connected) {
          this.stompClient.disconnect();
        }
      }
    },
    
    // 订阅私有队列
    subscribeToPrivateQueue() {
      if (!this.stompClient || !this.stompClient.connected) return;

      if (this.privateSubscription) {
        this.privateSubscription.unsubscribe();
      }

      const userId = this.currentUser;
      this.privateSubscription = this.stompClient.subscribe(
        `/user/${userId}/queue/private`,
        (message) => {
          try {
            const msg = JSON.parse(message.body);
            this.handlePrivateMessage(msg);
          } catch (e) {
            console.error('消息解析失败:', e);
          }
        },
        { 
          'Authorization': `Bearer ${getToken()}`,
          'X-User-ID': this.currentUser,
          'id': `sub-${userId}-private`
        }
      );
    },
    
    // 订阅发送确认队列
    subscribeToSentQueue() {
      if (!this.stompClient || !this.stompClient.connected) return;

      if (this.sentSubscription) {
        this.sentSubscription.unsubscribe();
      }

      const userId = this.currentUser;
      this.sentSubscription = this.stompClient.subscribe(
        `/user/${userId}/queue/sent`,
        (message) => {
          const msg = JSON.parse(message.body);
          console.log('发送确认:', msg);
        },
        { 
          'Authorization': `Bearer ${getToken()}`,
          'id': `sub-${userId}-sent`
        }
      );
    },
    
    // 启动心跳检测
    startHeartbeat() {
      this.heartbeatInterval = setInterval(() => {
        if (!this.stompClient.connected) {
          console.warn('心跳检测: 连接断开，尝试重连...');
          this.initWebSocket();
        }
      }, 15000);
    },
    
    // 处理连接错误
    handleConnectionError(error) {
      if (this.reconnectAttempts < this.maxReconnectAttempts) {
        this.reconnectAttempts++;
        const delay = Math.min(5000 * Math.pow(2, this.reconnectAttempts), 30000);
        setTimeout(() => this.initWebSocket(), delay);
      } else {
        this.$message.error('连接失败，请刷新页面');
      }
    },
    
    // 处理收到的私聊消息
    handlePrivateMessage(msg) {
      if (!msg.sender || !msg.receiver || !msg.content) {
        console.error('无效消息结构:', msg);
        return;
      }

      // 确保消息属于当前会话
      const isCurrentChat = 
        (msg.sender === this.currentChat.userId && msg.receiver === this.currentUser) ||
        (msg.receiver === this.currentChat.userId && msg.sender === this.currentUser);
      
      if (isCurrentChat) {
        this.messages.push({
          ...msg,
          isSelf: msg.sender === this.currentUser
        });
        this.scrollToBottom();
        
        if (msg.sender !== this.currentUser) {
          this.sendReadReceipt(msg.id);
        }
      }
      
      // 更新会话列表
      this.updateConversationList(msg);
    },
    
    // 更新会话列表
    updateConversationList(msg) {
      const participants = [msg.sender, msg.receiver].sort();
      const sessionKey = `private_${participants.join('_')}`;
      
      let conv = this.privateConversations.find(c => c.sessionKey === sessionKey);
      if (!conv) {
        conv = {
          id: sessionKey,
          sessionKey,
          userId: msg.sender === this.currentUser ? msg.receiver : msg.sender,
          name: msg.sender === this.currentUser ? msg.receiverName : msg.senderName,
          avatar: msg.sender === this.currentUser ? msg.receiverAvatar : msg.senderAvatar,
          lastMessage: msg.content,
          lastMessageTime: msg.createTime,
          unreadCount: 0
        };
        this.privateConversations.unshift(conv);
      } else {
        conv.lastMessage = msg.content;
        conv.lastMessageTime = msg.createTime;
      }
      
      // 如果当前不在聊天窗口，增加未读计数
      if (!this.showChatDialog || this.currentChat.sessionKey !== sessionKey) {
        conv.unreadCount += 1;
      }
    },
    
    // 打开聊天对话框
    async openChat(conversation) {
      if (conversation.itemId) {
        this.$router.push({ path: '/details', query: { id: conversation.itemId } });
        return;
      }
      
      if (!this.checkAuth()) return;
      
      this.currentChat = {
        ...conversation,
        type: 'private',
        sessionKey: conversation.sessionKey
      };
      
      this.showChatDialog = true;
      
      try {
        if (!this.stompClient || !this.stompClient.connected) {
          await this.initWebSocket();
        }
        
        this.loadChatHistory();
        this.focusInput();
        
        // 标记已读
        if (conversation.unreadCount > 0) {
          this.markAsRead(conversation.sessionKey);
          conversation.unreadCount = 0;
        }
      } catch (error) {
        console.error('打开聊天失败:', error);
        this.$message.error('无法建立聊天连接');
      }
    },
    
    // 加载聊天历史
    loadChatHistory() {
      if (!this.currentChat.userId) return;
      
      this.$api.service.get('/chat/private-history', {
        params: { targetUser: this.currentChat.userId }
      }).then(res => {
        if (res.status_code === 1) {
          this.messages = res.data.map(msg => ({
            ...msg,
            isSelf: msg.sender === this.currentUser
          }));
          this.scrollToBottom();
        }
      }).catch(console.error);
    },
    
    // 发送消息
    async sendMessage() {
      if (!this.newMessage.trim()) {
        this.$message.error("消息不能为空！");
        return;
      }
      
      if (!this.currentUser || !this.currentChat.userId) {
        this.$message.error("用户信息未加载完成");
        return;
      }

      const message = {
        content: this.newMessage.trim(),
        sender: this.currentUser,
        receiver: this.currentChat.userId,
        createTime: new Date().toISOString()
      };

      try {
        if (!this.stompClient.connected) {
          await this.initWebSocket();
        }
        
        await this.stompClient.safeSend('/app/private', message);
        
        // 乐观更新
        this.messages.push({
          ...message,
          isSelf: true
        });
        this.newMessage = '';
        this.scrollToBottom();
        
      } catch (e) {
        console.error('发送失败:', e);
        this.$message.error('发送消息失败');
      }
    },
    
    // 发送阅读回执
    sendReadReceipt(messageId) {
      this.$api.service.post('/chat/mark-read', { messageId })
        .catch(console.error);
    },
    
    // 标记为已读
    markAsRead(messageId) {
      console.log('标记消息已读', messageId);
      this.$api.service.post(`/chat/mark-read`,{messageId:messageId}).then(() => {})
    },
    
    // 删除聊天
    deleteChat() {
  if (!this.currentChat) return;
  
  this.$confirm('确定要删除此聊天记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (this.currentChat.type === 'private') {
      console.log('删除私有会话', this.currentChat);
      const ids = this.messages.map(m => m.id);
      const lastsender = this.messages[this.messages.length - 1].sender;
      const lastreceiver = this.messages[this.messages.length - 1].receiver;
      
      this.$api.service.post('/chat/delete', {
        messageIds: ids,
        senderId: lastsender,
        receiverId: lastreceiver
      }).then(() => {
        this.privateConversations = this.privateConversations.filter(
          c => c.userId !== this.currentChat.userId
        );
        this.closeChat();
        this.$message.success('删除成功');
      }).catch(error => {
        let errorMsg = '删除失败';
        if (error.response && error.response.data && error.response.data.message) {
          errorMsg = error.response.data.message;
        }
        this.$message.error(errorMsg);
      });
    } else {
      this.$api.service.get('/message/delete', {
        params: { idleId: this.currentChat.itemId }
      }).then(() => {
        this.messageConversations = this.messageConversations.filter(
          c => c.itemId !== this.currentChat.itemId
        );
        this.closeChat();
        this.$message.success('删除成功');
      }).catch(error => {
        let errorMsg = '删除失败';
        if (error.response && error.response.data && error.response.data.message) {
          errorMsg = error.response.data.message;
        }
        this.$message.error(errorMsg);
      });
    }
  }).catch(() => {
    this.$message({
      type: 'info',
      message: '已取消删除'
    });
  });
},
    
    // 关闭聊天对话框
    closeChat() {
      this.showChatDialog = false;
      this.currentChat = {};
    },
    
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageContainer;
        if (container) container.scrollTop = container.scrollHeight;
      });
    },
    
    // 对话框打开后自动聚焦输入框
    focusInput() {
      this.$nextTick(() => {
        const input = this.$refs.messageInput;
        if (input && input.focus) {
          input.focus();
        }
      });
    },
    
    // 格式化时间
    formatTime(time) {
      return time ? dayjs(time).format('YYYY-MM-DD HH:mm') : '';
    },
    
    // 获取默认头像
    getDefaultAvatar(userId) {
      const i = userId ? userId % (this.defaultAvatars.length || 5) : 0;
      return this.defaultAvatars[i];
    }
  }
}
</script>

<style scoped>
.message-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.message-header {
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.conversation-list {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.3s;
}

.conversation-item:hover {
  background-color: #f5f7fa;
}

.conversation-item.unread {
  background-color: #f0f9eb;
}

.conversation-info {
  flex: 1;
  margin-left: 15px;
}

.info-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.username {
  font-weight: bold;
}

.time {
  color: #999;
  font-size: 12px;
}

.preview {
  color: #666;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-message {
  text-align: center;
  padding: 40px;
}

.empty-message img {
  width: 200px;
  margin-bottom: 20px;
}

.empty-message p {
  color: #999;
}

.chat-dialog {
  display: flex;
  flex-direction: column;
}

.chat-messages {
  height: 400px;
  overflow-y: auto;
  padding: 20px;
  background: #f5f7fa;
  margin-bottom: 20px;
}

.message-item {
  margin-bottom: 15px;
}

.message-item.self {
  text-align: right;
}

.message-user {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.sender-name {
  font-size: 14px;
  color: #606266;
}

.self-name {
  order: 1;
  margin-right: 8px;
}

.message-content {
  display: inline-block;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f0f2f5;
  max-width: 70%;
  word-break: break-word;
}

.message-item.self .message-content {
  background-color: #409eff;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.chat-input-container {
  display: flex;
  gap: 10px;
}

.chat-input {
  flex: 1;
}

.send-button {
  height: auto;
  align-self: flex-end;
}

.item-preview {
  margin-left: 15px;
}

.unread-badge {
  margin-left: 10px;
}

.chat-dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  width: 100%;
}

.chat-dialog-title {
  margin-left: 15px;
  flex-grow: 1;
}

.chat-user-name {
  font-size: 18px;
  font-weight: bold;
}

.chat-user-id {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.custom-chat-dialog .el-dialog__header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}
</style>